<template>
    <el-form :model="activityForm" :inline="true" style="margin-bottom: 10px;" class="demo-form-inline">
        <el-form-item label="培训名称">
            <el-input v-model="activityForm.trainingName" style="width: 150px;" placeholder="请输入培训名称" />
        </el-form-item>
        <el-form-item label="活动状态">
            <el-select v-model="activityForm.activityStatus" clearable style="width: 150px;" placeholder="请选择">
                <el-option label="正在进行" value="1"></el-option>
                <el-option label="已经结束" value="2"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="开展时间">
            <el-date-picker v-model="activityForm.date" clearable value-format="YYYY-MM-DD" type="daterange"
                placeholder="选择日期" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                style="width: 300px; margin-left: 10px"></el-date-picker>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="getActivityInfo">查询</el-button>
            <el-button type="info" @click="clearActivityForm">清空</el-button>
        </el-form-item>
    </el-form>
    <!-- 表格 -->
    <el-table :data="userTableData" border style="width: 100%;margin-bottom: 10px;margin-top: 10px;">
        <el-table-column type="index" label="id" width="40" />
        <el-table-column property="trainingName" label="培训名称" width="120" />
        <el-table-column property="maxCapacity" label="人数上限" width="120" />
        <el-table-column property="actualAttendance" label="实时参加人数" width="120" />
        <el-table-column property="startTime" label="开展时间" width="120" />
        <el-table-column property="endTime" label="结束时间" width="120" />
        <el-table-column property="activityStatus" label="活动状态" width="120">
            <template #default="scope">
                <el-tag v-if="scope.row.activityStatus === 1" type="success">正在进行</el-tag>
                <el-tag v-else-if="scope.row.activityStatus === 2" type="info">已经结束</el-tag>
            </template>
        </el-table-column>
        <el-table-column property="registrationStatus" label="报名状态" width="120">
            <template #default="scope">
                <el-tag v-if="scope.row.registrationStatus === 1" type="success">已报名</el-tag>
                <el-tag v-else-if="scope.row.registrationStatus === 2" type="info">未报名</el-tag>
            </template>
        </el-table-column>
        <el-table-column style="justify-content: space-between;" label="操作">
            <template #default="scope">
                <el-link type="primary" style="margin-right: 10px;"
                    @click="registration(scope.row.id, scope.row.trainingName, scope.row.maxCapacity, scope.row.actualAttendance, scope.row.activityStatus)">报名</el-link>
                <el-link target="_blank" style="margin-right: 10px;"
                    @click="checkTrainingDetail(scope.row.id, scope.row.trainingName,scope.row.trainingPlan)">查看详情</el-link>
                <el-link type="danger" @click="cancelRegistration(scope.row.id)">取消报名</el-link>
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页条 -->
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
        :size="size" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
        :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    <!-- 报名 -->
    <el-dialog v-model="registerDialogVisible" title="团建报名" draggable center style="width: 50%;">
        <el-card style="width: 50%;margin-left: 150px;">
            <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
                class="demo-ruleForm" :size="formSize" status-icon>
                <el-form-item label="培训名称" prop="trainingName">
                    <el-input v-model="ruleForm.trainingName" placeholder="请输入培训名称" style="width: 190px;" />
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="ruleForm.name" placeholder="请输入你的姓名" style="width: 190px;" />
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-select v-model="ruleForm.gender" clearable placeholder="请选择性别" style="width: 190px;">
                        <el-option label="男" value="1"></el-option>
                        <el-option label="女" value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="账号" prop="account">
                    <el-input v-model="ruleForm.account" placeholder="请输入你的账号" style="width: 190px;" />
                </el-form-item>
                <el-form-item label="报名时间" prop="registrationTime">
                    <el-date-picker v-model="ruleForm.registrationTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择报名时间"
                        style="width: 190px;" :size="size" />
                </el-form-item>
                <el-form-item style="justify-items: center;">
                    <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
                    <el-button @click="resetForm(ruleFormRef)">清空</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </el-dialog>
    <!-- 详情对话框 -->
    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="查看详情" draggable center>
        <el-form :model="form" label-width="auto" style="max-width: 100%">
            <el-form-item label="培训名称:">
                {{ form.trainingName }}
            </el-form-item>
            <el-form-item label="培训计划:">
                {{ form.trainingPlan }}
            </el-form-item>
            <el-form-item label="你的活动时长:">
                {{ form.activityDuration }}
            </el-form-item>
            <el-form-item label="你的培训得分:">
                {{ form.activityScore }}
            </el-form-item>
        </el-form>
    </el-dialog>
</template>


<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'
import axios from '@/utils/request';
import moment from 'moment';
import { empAccount } from '@/store';
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const registerDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const size = ref<ComponentSize>('default')
const background = ref(true)
const disabled = ref(false)
const account = ref(empAccount().$state.account)
const gender = ref(empAccount().$state.gender)
const name = ref(empAccount().$state.name)
const ruleForm = reactive({
    id: '',
    trainingName: '',
    name: '',
    gender: '',
    account: '',
    registrationTime:''
})
//获取当前时间
ruleForm.registrationTime = moment().format('YYYY-MM-DD HH:mm:ss')
ruleForm.account = account.value
ruleForm.gender = gender.value == '1' ? '1' : '2'
ruleForm.name = name.value
const form = ref({
    trainingName: '',
    trainingPlan: '',
    activityDuration: '',
    activityScore: ''
})
let activityForm = ref({
    trainingName: '',
    activityStatus: '',
    date: ['', '']
})
const clearActivityForm = () => {
    activityForm.value.trainingName = '';
    activityForm.value.activityStatus = '';
    activityForm.value.date = ['', ''];
    // 刷新表格数据
    getActivityInfo(null);
}

const userTableData = ref([])
const rules = reactive<FormRules>({
    name: [
        { required: true, message: '姓名不能为空', trigger: 'blur' },
    ],
    account: [
        { required: true, message: '账号不能为空', trigger: 'blur', },
    ],
    registrationTime: [
        { required: true, message: '时间不能为空', trigger: 'change', },
    ],
    gender: [
        { required: true, message: '性别不能为空', trigger: 'change', },
    ],
    trainingName: [
        { required: true, message: '培训名称不能为空', trigger: 'blur', },
    ],
})
//获取活动信息
const getActivityInfo = async (id: any) => {
    try {
        const result = await axios.get(`/emp/trainingActivity`, {
            params: {
                account: account.value,
                trainingName: activityForm.value.trainingName,
                activityStatus: activityForm.value.activityStatus,
                start: activityForm.value.date[0],
                end: activityForm.value.date[1]
            }
        })
        if (result.data.code === 1) {
            if (activityForm.value.date[0] !== '' || activityForm.value.date[1] !== '' ||
                activityForm.value.trainingName !== '' || activityForm.value.activityStatus !== '') {
                ElMessage.success('查询成功')
            }
            userTableData.value = result.data.data.rows
            total.value = result.data.data.total
        } else {
            ElMessage.error('查询失败')
        }
    } catch (error) {
        console.log(error)
    }
}
//员工培训活动的报名
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            const result = await axios.post('/emp/trainingActivity', ruleForm)
            if (result.data.code === 1) {
                ElMessage.success('报名成功')
                //关闭对话框
                registerDialogVisible.value = false
                //刷新数据
                getActivityInfo(null)
            } else {
                ElMessage.error('报名失败')
            }
        } else {
            ElMessage.error('请填写正确的信息')
        }
    })
}
//查看详情
const checkTrainingDetail = async (id: any, trainingName: any,trainingPlan :any) => {
    form.value.trainingName = trainingName
    form.value.trainingPlan = trainingPlan 
    //打开详情对话框
     detailDialogVisible.value = true
    //再去请求剩余的信息，员工培训信息表
    try {
        const result = await axios.get(`/emp/trainingActivity/${id}`, {
            params: {
                account: account.value,
                trainingName: trainingName
            }
        })
        if (result.data.code == 1) {
            form.value.activityDuration = result.data.data.activityDuration
            form.value.activityScore = result.data.data.activityScore
            if (result.data.data==null) {
                form.value.activityDuration = '你还没有报名'
                form.value.activityScore = '你还没有报名'
            }
            console.log(result)
        } else {
            ElMessage.error('查询失败')
        }
    } catch (error) {
        console.log(error)
    }
}
//取消报名
const cancelRegistration = async (id: any) => {
    //防止误触
    const isConfirm = window.confirm('确定取消吗？')
    if (!isConfirm) {
        return
    }
    try {
        const result = await axios.delete(`/emp/trainingActivity`, {
            params: {
                id: id,
                account: account.value
            }
        })
        if (result.data.code === 1) {
            ElMessage.success('取消成功')
            //刷新数据
            getActivityInfo(null)
        } else {
            ElMessage.error('取消失败')
        }
    } catch (error) {
        console.log(error)
    }
}
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

//当前页改变时触发
const handleCurrentChange = (val: number) => {
    currentPage.value = val;
}
//每页条数改变时触发
const handleSizeChange = (val: number) => {
    pageSize.value = val;
}
//报名时触发函数
const registration = (id: string, trainingName: string, maxCapacity: any, actualAttendance: any, activityStatus: any) => {
    //判断当前报名人数是否已满
    if (actualAttendance >= maxCapacity) {
        ElMessage.error('当前报名人数已满')
        return
    }
    //判断当前活动是否已经结束
    if (activityStatus == '2') {
        ElMessage.error('当前活动已经结束')
        return
    }
    //将id和培训名称传递给ruleForm
    ruleForm.trainingName = trainingName
    ruleForm.id = id
    //打开报名对话框
    registerDialogVisible.value = true
}
</script>

<style></style>